package controllers

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"UpdateManagerServer/dbmgr"
	"UpdateManagerServer/models"

	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/server/web"
	beego "github.com/beego/beego/v2/server/web"
)

type MainController struct {
	beego.Controller
}

func (c *MainController) Get() {
	c.Data["Website"] = "beego.vip"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "index.tpl"
}

type LoginController struct {
	beego.Controller
}

func (c *LoginController) Get() {
	c.Data["Website"] = "beego.vip"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "login.tpl"
}

type PermissionController struct {
	beego.Controller
}

func (c *PermissionController) Get() {
	c.Data["Website"] = "beego.vip"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "permissionEdit.tpl"
}

type VersionPageController struct {
	beego.Controller
}

func (c *VersionPageController) Get() {
	c.Data["Website"] = "beego.vip"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "fileWindowBox.tpl"
}

type VersionListController struct {
	beego.Controller
}

type Version struct {
	Id        string    `json:"id"`        // 唯一标识
	Name      string    `json:"name"`      // 版本名称
	Version   string    `json:"version"`   // 版本号
	Creator   string    `json:"creator"`   // 创建人
	CreatedAt time.Time `json:"createdAt"` // 创建时间
	Remark    string    `json:"remark"`    // 备注说明
}

// models/version.go
type VersionListResponse struct {
	Code     int        `json:"code"`
	Data     []*Version `json:"data"`
	Total    int64      `json:"total"`
	Page     int        `json:"page"`
	PageSize int        `json:"pageSize"`
}

// Get 获取版本列表
// @Title 获取版本列表
// @Description 分页获取版本数据
// @Param   page      query   int     false   "页码"
// @Param   pageSize  query   int     false   "每页数量"
// @Param   search    query   string  false   "搜索关键词"
// @Success 200 {object} models.VersionListResponse
// @Failure 500 服务器错误
// @router / [get]
func (c *VersionListController) GetVersionList() {
	// 参数解析
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("pageSize", 10)
	machineID, _ := c.GetInt("machineID", 0)
	//search := c.GetString("search")

	// 参数校验
	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 100 {
		pageSize = 10
	}

	var queryVersion dbmgr.Version
	var queryMechine dbmgr.Machine
	queryMechine.Id = machineID
	queryVersion.Machine = &queryMechine
	// 查询数据
	data, total, err := dbmgr.GlobalBaseRepo.List_versions(page, pageSize, &queryVersion)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": err.Error(),
		}
		c.ServeJSON()
		return
	}

	var responseData []interface{}
	for _, indexItem := range data {
		mapData := make(map[string]interface{})

		strTimeFormat, err := models.Convert2BeijingTimeFormat(indexItem.CreatedAt)
		if err != nil {
			logs.Error("转换iso时间格式失败, err:%s", err.Error())
			c.Data["json"] = map[string]interface{}{
				"code":    500,
				"message": err.Error(),
			}
			c.ServeJSON()
			return
		}

		mapData["Name"] = indexItem.Name
		mapData["Version"] = indexItem.Version
		mapData["CreatedAt"] = strTimeFormat
		mapData["Creator"] = indexItem.Creator
		mapData["Id"] = indexItem.Id

		responseData = append(responseData, mapData)
	}

	// 格式化响应
	response := map[string]interface{}{
		"code":     200,
		"data":     responseData,
		"total":    total,
		"page":     page,
		"pageSize": pageSize,
	}
	c.Data["json"] = response
	c.ServeJSON()
}

func (c *VersionListController) GetVersionInfoByID() {
	version := c.GetString("version")
	//search := c.GetString("search")

	versionInfo, err := dbmgr.GlobalBaseRepo.Get_version(version)
	if err != nil {
		logs.Error(err.Error())
		c.Data["json"] = map[string]interface{}{
			"code":    200,
			"message": "获取最新版本失败,err:" + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 格式化响应
	response := map[string]interface{}{
		"code": 0,
		"data": versionInfo,
	}
	c.Data["json"] = response
	c.ServeJSON()
}

func (c *VersionListController) GetVersionMax() {
	machineCode := c.GetString("machineCode")
	//search := c.GetString("search")

	machineInfo, err := dbmgr.GlobalBaseRepo.GetMachineByCode(machineCode)
	if err != nil {
		logs.Error(err.Error())
		c.Data["json"] = map[string]interface{}{
			"code":    200,
			"message": "获取最新版本失败,err:" + err.Error(),
		}
		c.ServeJSON()
		return
	}

	versionInfo, err := dbmgr.GlobalBaseRepo.GetLatestVersionByMachine(machineInfo.Id)
	if err != nil {
		logs.Error(err)
		c.Data["json"] = map[string]interface{}{
			"code":    200,
			"message": "获取最新版本失败,err:" + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 格式化响应
	response := map[string]interface{}{
		"code": 200,
		"data": versionInfo,
	}
	c.Data["json"] = response
	c.ServeJSON()
}

// Post 处理创建版本请求
func (c *VersionListController) PostAddVersion() {
	// 解析 JSON 请求体
	var requestData struct {
		Name      string `json:"name"`
		Version   string `json:"version"`
		Created   string `json:"created"` // 前端传字符串
		Creator   string `json:"creator"`
		Remark    string `json:"remark"`
		MachineID int    `json:"machine_id"`
	}

	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
		c.Data["json"] = map[string]interface{}{"code": "400", "message": "无效的JSON格式"}
		c.Data["code"] = "400"
		logs.Error("无效的JSON格式, msg:%s", c.Ctx.Input.RequestBody)
		c.ServeJSON()
		return
	}

	if requestData.Name == "" {
		c.Data["json"] = map[string]interface{}{"code": "400", "message": "版本名称为空"}
		c.Data["code"] = "200"
		logs.Error("版本名称为空")
		c.ServeJSON()
		return
	}

	var createTime time.Time
	var err error
	if requestData.Created == "" {
		createTime = time.Now()
	} else {
		// 转换时间格式
		createTime, err = time.Parse("2006-01-02 15:04", requestData.Created)
		if err != nil {
			c.Data["json"] = map[string]interface{}{"code": "400", "message": "时间格式必须为 YYYY-MM-DD HH:mm"}
			logs.Error("时间格式错误, err:%s", err.Error())
			c.ServeJSON()
			return
		}
	}

	var machineInfo dbmgr.Machine
	machineInfo.Id = requestData.MachineID

	tokenStr := c.Ctx.Input.Header("Authorization")
	//logs.Debug("get submitter token: %s", tokenStr)
	tokenInfo, err := dbmgr.GlobalBaseRepo.GetByToken(tokenStr)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    "400",
			"message": "根据token获取用户信息失败 err:" + err.Error(),
		}
		c.ServeJSON()
		return
	}

	employeeInfo, err := dbmgr.GlobalBaseRepo.Get_employeeByID(tokenInfo.User.ID)
	if err != nil {
		logs.Error(err.Error())
		c.Data["json"] = map[string]interface{}{
			"code":    "400",
			"message": "获取用户信息失败" + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 写入数据库
	version := dbmgr.Version{
		Name:      requestData.Name,
		CreatedAt: createTime,
		CreatorId: employeeInfo.ID,
		Creator:   employeeInfo.Account,
		Remark:    requestData.Remark,
		Machine:   &machineInfo,
	}

	uid, err := dbmgr.GlobalBaseRepo.Add_version(&version)
	if err != nil {
		c.Data["json"] = map[string]interface{}{"code": "400", "message": "数据库写入失败"}
		logs.Error("数据库写入失败, err:%s", err.Error())
		c.ServeJSON()
		return
	}

	// 创建文件目录（新增代码）
	basePath := "FileList" // 建议配置化
	targetDir := filepath.Join(basePath, uid)

	// 带权限的目录创建（推荐方案）
	if err := os.MkdirAll(targetDir, 0755); err != nil {
		// 错误处理建议
		c.Data["json"] = map[string]interface{}{
			"message": "目录创建失败: " + err.Error(),
			"code":    "200",
		}
		logs.Error("目录创建失败: %s", err.Error())
		c.ServeJSON()

		return
	}

	// 返回成功响应
	c.Data["json"] = map[string]interface{}{
		"id":      version.Id,
		"code":    "0",
		"message": "版本创建成功",
	}
	c.ServeJSON()
}

type DeleteRequest struct {
	ID string `json:"id"`
}

func (c *VersionListController) PostDeleteVersion() {
	// 设置JSON响应头
	c.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json")

	// 解析请求参数
	var req DeleteRequest
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    "400",
			"message": "无效的请求参数",
		}
		logs.Error("无效的请求参数, %s", c.Ctx.Input.RequestBody)
		c.ServeJSON()
		return
	}

	// 参数校验
	if req.ID == "" {
		c.Data["json"] = map[string]interface{}{
			"code":    "400",
			"message": "版本ID不能为空",
		}

		logs.Error("版本ID不能为空, %s", c.Ctx.Input.RequestBody)
		c.ServeJSON()
		return
	}

	// 数据库操作
	if err := dbmgr.GlobalBaseRepo.DeleteVersionWithFiles(req.ID); err != nil {
		logs.Error("删除版本失败:", err)
		c.Data["json"] = map[string]interface{}{
			"code":    "500",
			"message": "删除版本失败: " + err.Error(),
		}
		logs.Error("删除版本失败, %s", err.Error())
		c.ServeJSON()
		return
	}

	// 返回成功响应
	c.Data["json"] = map[string]interface{}{
		"code":    "0",
		"message": "删除成功",
	}
	c.ServeJSON()
}

type FileSubmitInfo struct {
	Name string `json:"name"`
}

type UploadRequest struct {
	FileList  []FileSubmitInfo `json:"fileList" valid:"Required"`
	ReqCode   string           `json:"reqcode" valid:"Required"`
	VersionID string           `json:"version" valid:"Required"`
}

func (c *VersionListController) PostAddSubVersion() {
	logs.Debug("PostAddSubVersion, recv: %s", c.Ctx.Input.RequestBody)

	// 解析请求体
	var req UploadRequest

	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    "400",
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	var subVersionInfo dbmgr.FileSubmission
	nNewID, err := dbmgr.GlobalBaseRepo.GenerateSubmissionNumber()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    "400",
			"message": "获取新的提交id失败， err:" + err.Error(),
		}
		c.ServeJSON()
		return
	}

	tokenStr := c.Ctx.Input.Header("Authorization")
	logs.Debug("get submitter token: %s", tokenStr)
	tokenInfo, err := dbmgr.GlobalBaseRepo.GetByToken(tokenStr)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    "400",
			"message": "根据token获取用户信息失败 err:" + err.Error(),
		}
		c.ServeJSON()
		return
	}

	logs.Debug("get subitter tokeninfo: %v", tokenInfo)

	subVersionInfo.SubmissionNumber = nNewID
	loc, _ := time.LoadLocation("Asia/Shanghai")
	subVersionInfo.Remark = "提交记录：" + time.Now().In(loc).String()
	subVersionInfo.SubmittedAt = time.Now()
	subVersionInfo.Submitter = tokenInfo.User.ID
	subVersionInfo.VersionID = req.VersionID

	subVersionInfo.ID, err = dbmgr.GlobalBaseRepo.AddSubmission(&subVersionInfo)
	if err != nil {
		logs.Error("添加上传记录失败, err:%s, data:%v", err.Error(), subVersionInfo)
		c.Data["json"] = map[string]interface{}{
			"code":    "400",
			"message": "添加上传记录失败 err:" + err.Error(),
		}
		c.ServeJSON()
		return
	}

	for _, fileSubIndex := range req.FileList {
		var fileSubItemInfo dbmgr.FileSubItem
		fileSubItemInfo.FileName = fileSubIndex.Name
		fileSubItemInfo.FileSubmission = &subVersionInfo
		err = dbmgr.GlobalBaseRepo.AddFileSubItem(&fileSubItemInfo)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"code":    "400",
				"message": "添加文件记录失败 err:" + err.Error(),
			}
			c.ServeJSON()
			return
		}
	}

	// 成功响应
	c.Data["json"] = ApiResponse{
		Code:    "0",
		Message: "sucess",
	}
	c.ServeJSON()
}

type FileListController struct {
	beego.Controller
}

func (c *FileListController) Get() {
	c.Data["Website"] = "beego.vip"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "fileExplor.tpl"
}

type PackDownloadListController struct {
	beego.Controller
}

func (c *PackDownloadListController) Get() {
	c.Data["Website"] = "beego.vip"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "downloadList.tpl"
}

type FileController struct {
	beego.Controller
}

type FileInfo struct {
	Name   string `json:"name"`     // 文件/文件夹名称
	Type   string `json:"type"`     // 文件类型（如 txt、jpg）
	IsDir  bool   `json:"isDir"`    // 是否为文件夹
	Path   string `json:"path"`     // 完整路径（用于递归请求）‌:ml-citation{ref="1,2" data="citationList"}
	Md5    string `json:"md5"`      // 完整路径（用于递归请求）‌:ml-citation{ref="1,2" data="citationList"}
	TaskTp string `json:"taskType"` //conf 配置文件  proc 执行程序文件
	ID     string `json:"id"`       //conf 配置文件  proc 执行程序文件
	Size   int64  `json:"size"`
}

func (c *FileController) DownloadFile() {
	var req struct {
		Path   string `json:"path"`
		Name   string `json:"name"`
		Method string `json:"method"`
	}

	_ = json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	//filename := req.Name
	filePath := req.Path

	// 检查文件是否存在
	fileInfo, err := os.Stat(filePath)
	if os.IsNotExist(err) {
		c.Ctx.ResponseWriter.WriteHeader(http.StatusNotFound)
		logs.Error("file not exit, path:%s", filePath)
		return
	}
	fileSize := fileInfo.Size()

	if req.Method == "getSize" {
		c.Data["json"] = map[string]string{"code": "0", "fileSize": strconv.FormatInt(fileSize, 10)}
		c.ServeJSON()
		return
	}

	// 解析 Range 请求头
	rangeHeader := c.Ctx.Request.Header.Get("Range")
	if rangeHeader == "" {
		http.ServeFile(c.Ctx.ResponseWriter, c.Ctx.Request, filePath)
		return
	}

	// 处理 Range 请求头（示例：bytes=0-1023）
	rangeParts := strings.Split(rangeHeader, "=") // 分割为 ["bytes", "0-1023"]
	if len(rangeParts) != 2 || rangeParts[0] != "bytes" {
		c.Ctx.ResponseWriter.WriteHeader(http.StatusBadRequest)
		logs.Error("error range format")
		return
	}

	parts := strings.Split(rangeParts[1], "-")
	start, _ := strconv.ParseInt(parts[0], 10, 64)
	end := fileSize - 1

	// 校验范围有效性
	if start > end || end >= fileSize {
		c.Ctx.ResponseWriter.WriteHeader(http.StatusRequestedRangeNotSatisfiable)
		logs.Error("error range size")
		return
	}

	// 设置分片响应头
	c.Ctx.ResponseWriter.Header().Set("Content-Range",
		fmt.Sprintf("bytes %d-%d/%d", start, end, fileSize))
	c.Ctx.ResponseWriter.Header().Set("Accept-Ranges", "bytes")
	c.Ctx.ResponseWriter.Header().Set("Content-Length", strconv.FormatInt(end-start+1, 10))
	c.Ctx.ResponseWriter.WriteHeader(http.StatusPartialContent)                                  // 206 状态码‌:ml-citation{ref="3" data="citationList"}
	c.Ctx.Output.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", req.Name)) // 强制下载‌:ml-citation{ref="4,5" data="citationList"}

	// 读取并返回分片数据
	file, _ := os.Open(filePath)
	defer file.Close()
	file.Seek(start, 0) // 定位到起始位置‌:ml-citation{ref="3" data="citationList"}
	buffer := make([]byte, end-start+1)
	file.Read(buffer)
	c.Ctx.ResponseWriter.Write(buffer)
}

func (c *FileController) DownloadFileEx() {
	var req struct {
		Path   string `json:"path"`
		Name   string `json:"name"`
		Method string `json:"method"`
		ID     string `json:"id"`
	}

	// 错误处理：反序列化失败时返回400
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
		c.Ctx.Output.SetStatus(http.StatusBadRequest)
		logs.Error("Invalid request body: %v, requset: %s", err, c.Ctx.Input.RequestBody)
		return
	}

	decodePath, err := url.QueryUnescape(req.Path)
	if err != nil {
		c.Ctx.Output.SetStatus(http.StatusBadRequest)
		logs.Error("Path decode error: %v", err)
		return
	}

	req.Path = decodePath

	decodedName, err := url.QueryUnescape(req.Name)
	if err != nil {
		c.Ctx.Output.SetStatus(http.StatusBadRequest)
		logs.Error("Name decode error: %v", err)
		return
	}

	req.Name = decodedName

	logs.Info("req: %v", req)

	bExit := dbmgr.GlobalBaseRepo.CheckFileExit(req.ID)

	if !bExit {
		logs.Error("文件不存在, id:%s", req.ID)
		c.Ctx.Output.SetStatus(http.StatusBadRequest)
		return
	}

	filePath := filepath.Join(req.Path, req.Name)

	filePath = strings.ReplaceAll(filePath, "\\", "/")

	// 获取文件元信息（增加错误处理）
	fileInfo, err := os.Stat(filePath)
	if err != nil {
		if os.IsNotExist(err) {
			c.Ctx.Output.SetStatus(http.StatusNotFound)
			logs.Error("File not found: %s", filePath)
		} else {
			c.Ctx.Output.SetStatus(http.StatusInternalServerError)
			logs.Error("Failed to stat file: %v", err)
		}
		return
	}

	// 新增：检查是否为文件夹
	if fileInfo.IsDir() {
		c.Ctx.Output.SetStatus(http.StatusBadRequest)
		logs.Error("Path is a directory: %s", filePath)
		return
	}

	// 处理获取文件大小请求
	if req.Method == "getSize" {
		c.Data["json"] = map[string]interface{}{
			"code":     "0",
			"fileSize": fileInfo.Size(),
		}
		c.ServeJSON()
		return
	}

	// 打开文件（增加错误处理）
	file, err := os.Open(filePath)
	if err != nil {
		c.Ctx.Output.SetStatus(http.StatusInternalServerError)
		logs.Error("Failed to open file: %v", err)
		return
	}
	defer file.Close()

	// 设置下载头信息
	c.Ctx.Output.Header("Content-Disposition",
		fmt.Sprintf("attachment; filename=%s", req.Name))
	c.Ctx.Output.Header("Content-Type", "application/octet-stream")

	// 使用高效的文件传输方法
	http.ServeContent(c.Ctx.ResponseWriter, c.Ctx.Request,
		req.Name, fileInfo.ModTime(), file)
}

type Md5Cache map[string]string

// 获取文件列表（JSON格式）
func (c *FileController) PostFileList() {
	// 定义请求参数结构体
	type RequestBody struct {
		VersionID  string `json:"version_id"`
		MarchineID int    `json:"machine_id"`
		Path       string `json:"path"`
		ParentID   string `json:"parent_id"`
	}

	// 解析 JSON 请求体
	var req RequestBody
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"error":   "无效的请求格式: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	files, err := dbmgr.GlobalBaseRepo.GetFilesByVersionAndParentID(req.MarchineID, req.VersionID, req.ParentID)
	if err != nil {
		logErrMsg := "从数据库获取数据失败,err: " + err.Error()
		logs.Error(logErrMsg)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"error":   logErrMsg,
		}
		c.ServeJSON()
		return
	}

	var fileList []FileInfo
	for _, file := range files {
		info := FileInfo{
			Name:  file.FileName,
			IsDir: file.IsFolder,
			Path:  file.Path,
			Md5:   file.MD5,
			ID:    file.Id,
			Size:  file.FileSize,
		}

		fileList = append(fileList, info)
	}

	c.Data["json"] = fileList
	c.ServeJSON() // 自动返回JSON响应‌:ml-citation{ref="1,2" data="citationList"}
}

func (c *FileController) loadFileListByVersionAndParent(machineID int, versionID string, parent string) ([]FileInfo, error) {
	var fileList []FileInfo

	files, err := dbmgr.GlobalBaseRepo.GetFilesByVersionAndParentID(machineID, versionID, parent)
	if err != nil {
		logErrMsg := "获取root路径失败, err: " + err.Error()
		logs.Error(logErrMsg)
		return nil, errors.New(logErrMsg)
	}

	for _, fileIndex := range files {
		infoParent := FileInfo{
			Name:  fileIndex.FileName,
			IsDir: fileIndex.IsFolder,
			Path:  fileIndex.Path,
			Md5:   fileIndex.MD5,
			ID:    fileIndex.Id,
		}

		fileList = append(fileList, infoParent)

		arrayFile, err := dbmgr.GlobalBaseRepo.GetNestedFiles(fileIndex.Id)
		if err != nil {
			logErrMsg := "递归获取文件目录失败, err: " + err.Error()
			logs.Error(logErrMsg)

			return nil, errors.New(logErrMsg)
		}

		for _, itemIndex := range arrayFile {
			info := FileInfo{
				Name:  itemIndex.FileName,
				IsDir: itemIndex.IsFolder,
				Path:  itemIndex.Path,
				Md5:   itemIndex.MD5,
				ID:    itemIndex.Id,
			}

			fileList = append(fileList, info)
		}
	}

	return fileList, nil
}

func (c *FileController) GetFileListALL() {
	versionID := c.GetString("versionID") // 通过参数传递路径（如 ?path=subdir）
	machineID, _ := c.GetInt("machineID")

	processFiles, processTotalSize, err := dbmgr.GlobalBaseRepo.GetFileTree(versionID, machineID, "process")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	confFiles, confTotalSize, err := dbmgr.GlobalBaseRepo.GetFileTree(versionID, machineID, "conf")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"error":   err.Error(),
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"process": processFiles,
		"conf":    confFiles,
		"size":    processTotalSize + confTotalSize,
	}
	c.ServeJSON()
}

func (c *FileController) GetFile() {
	filePath := c.GetString("path")
	//filePath := validatePath(pathr)

	// 检查文件是否存在
	fileInfo, err := os.Stat(filePath)
	if os.IsNotExist(err) {
		c.Ctx.ResponseWriter.WriteHeader(http.StatusNotFound)
		logs.Error("file not exit, path:%s", filePath)
		return
	}
	fileSize := fileInfo.Size()

	// 解析 Range 请求头
	rangeHeader := c.Ctx.Request.Header.Get("Range")
	if rangeHeader == "" {
		// 无 Range 请求时返回完整文件
		http.ServeFile(c.Ctx.ResponseWriter, c.Ctx.Request, filePath) // 自动支持分片下载‌:ml-citation{ref="3" data="citationList"}
		return
	}

	// 处理 Range 请求头（示例：bytes=0-1023）
	rangeParts := strings.Split(rangeHeader, "=") // 分割为 ["bytes", "0-1023"]
	if len(rangeParts) != 2 || rangeParts[0] != "bytes" {
		c.Ctx.ResponseWriter.WriteHeader(http.StatusBadRequest)
		logs.Error("error range format")
		return
	}

	parts := strings.Split(rangeParts[1], "-")
	start, _ := strconv.ParseInt(parts[0], 10, 64)
	end := fileSize - 1

	// 校验范围有效性
	if start > end || end >= fileSize {
		c.Ctx.ResponseWriter.WriteHeader(http.StatusRequestedRangeNotSatisfiable)
		logs.Error("error range size")
		return
	}

	// 设置分片响应头
	c.Ctx.ResponseWriter.Header().Set("Content-Range",
		fmt.Sprintf("bytes %d-%d/%d", start, end, fileSize))
	c.Ctx.ResponseWriter.Header().Set("Accept-Ranges", "bytes")
	c.Ctx.ResponseWriter.Header().Set("Content-Length", strconv.FormatInt(end-start+1, 10))
	c.Ctx.ResponseWriter.WriteHeader(http.StatusPartialContent) // 206 状态码‌:ml-citation{ref="3" data="citationList"}

	// 读取并返回分片数据
	file, _ := os.Open(filePath)
	defer file.Close()
	file.Seek(start, 0) // 定位到起始位置‌:ml-citation{ref="3" data="citationList"}
	buffer := make([]byte, end-start+1)
	file.Read(buffer)
	c.Ctx.ResponseWriter.Write(buffer)
}

func (c *FileController) DeletFileDoc() {
	var req struct {
		Path    string `json:"path"`
		Name    string `json:"name"`
		Version string `json:"version"`
		Machine int    `json:"machine"`
		IsDir   bool   `json:"isDir"`
		ID      string `json:"id"`
	}

	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    "200",
			"message": "error json format",
		}

		logs.Error("unmarshal json failed, request: %s", c.Ctx.Input.RequestBody)
		c.Ctx.ResponseWriter.WriteHeader(400) // Bad Request
		c.ServeJSON()

		return
	}

	fileInfoDB, err := dbmgr.GlobalBaseRepo.GetFile(req.ID)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    "200",
			"message": "get file failed, err:" + err.Error(),
		}

		logs.Error("get file failed, err: %s", err.Error())
		c.Ctx.ResponseWriter.WriteHeader(400) // Bad Request
		c.ServeJSON()

		return
	}

	targetPath := filepath.Join(fileInfoDB.Path, fileInfoDB.FileName)

	err = dbmgr.GlobalBaseRepo.DeleteFileCascade(req.Machine, req.Version, req.ID)
	if err != nil {
		logs.Error("delete file info from db failed, version: %s, targert: %s", req.Version, targetPath)
		c.Data["json"] = map[string]interface{}{
			"code":    "200",
			"message": "delete file info from db failed",
		}
		c.ServeJSON()
		return
	}

	// 检查文件/目录是否存在
	fileInfo, err := os.Stat(targetPath)
	if err == nil {
		// 执行删除操作
		if fileInfo.IsDir() {
			err = os.RemoveAll(targetPath) // 删除目录及内容
		} else {
			err = os.Remove(targetPath) // 删除文件
		}

		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"code":    "200",
				"file":    req.Path,
				"message": "Failed to delete: " + err.Error(),
			}
			logs.Error("Failed to delete, err: %s", err.Error())
			c.Ctx.ResponseWriter.WriteHeader(500) // Internal Server Error
			c.ServeJSON()
			return
		}
	} else if os.IsNotExist(err) {
		strErrMsg := fmt.Sprintf("Path %s does not exist", targetPath)

		logs.Error(strErrMsg)

		c.Data["json"] = map[string]interface{}{
			"code":    "200",
			"file":    req.Path,
			"message": strErrMsg,
		}

		c.ServeJSON()
		return
	} else {
		logs.Error(err.Error())

		c.Data["json"] = map[string]interface{}{
			"code":    "200",
			"file":    req.Path,
			"message": err.Error(),
		}

		c.ServeJSON()
		return
	}

	err = dbmgr.GlobalBaseRepo.UpdateVersionFilesMD5(fileInfoDB.Version.Id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    "200",
			"message": err.Error(),
		}

		logs.Error(err.Error())

		c.ServeJSON()
		return
	}

	// 返回成功响应
	logs.Info("Successfully deleted: %s", targetPath)
	c.Data["json"] = map[string]interface{}{
		"code":    "0",
		"file":    req.Path,
		"message": "Deleted successfully",
	}
	c.Ctx.ResponseWriter.WriteHeader(200)
	c.ServeJSON()
}

func (c *FileController) RenameFile() {
	type Request struct {
		OldPath string `json:"old_path"`
		NewName string `json:"new_name"`
		ID      string `json:"id"`
	}

	var req Request
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
		logs.Error("json 格式错误, json: %s", c.Ctx.Input.RequestBody)

		c.Data["json"] = map[string]interface{}{
			"code":    "200",
			"message": "无效的请求格式",
		}
		c.ServeJSON()
		return
	}

	// 安全校验：防止路径遍历攻击
	baseDir := "FileList" // 替换为你的安全基础目录
	//fullPath := filepath.Join(baseDir, targetPath)
	//resolvedPath, err := filepath.EvalSymlinks(req.OldPath) // 解析符号链接
	if !strings.HasPrefix(req.OldPath, baseDir) {
		c.Data["json"] = map[string]interface{}{
			"code":    "200",
			"message": "Invalid path",
		}
		logs.Error("path error, path: %s", req.OldPath)
		c.Ctx.ResponseWriter.WriteHeader(403) // Forbidden
		c.ServeJSON()
		return
	}

	// 实际重命名操作
	if err := models.RenameFile(req.OldPath, req.NewName); err != nil {
		logs.Error("重命名失败, err:%s, oldpath: %s, newname: %s", err.Error(), req.OldPath, req.NewName)
		c.Data["json"] = map[string]interface{}{
			"code":    "200", // 业务失败代码
			"message": err.Error(),
		}

		c.ServeJSON()
		return
	} else {
		mapFileInfo := map[string]interface{}{
			"FileName": req.NewName,
		}
		err = dbmgr.GlobalBaseRepo.UpdateFileByID(req.ID, mapFileInfo)
		if err != nil {
			logs.Error("dbmgr.GlobalBaseRepo.UpdateFileByID failed, err:%s", err.Error())

			c.Data["json"] = map[string]interface{}{
				"code":    "200", // 业务失败代码
				"message": err.Error(),
			}

			c.ServeJSON()
			return
		}

		c.Data["json"] = map[string]interface{}{
			"code":    "0", // 成功代码
			"message": "操作成功",
		}
		c.ServeJSON()
		return
	}

}

type UploadController struct {
	beego.Controller
}

// 分片上传接口
func (c *UploadController) PostChunk() {
	// 获取上传参数
	file, _, _ := c.GetFile("file")
	uploadId := c.GetString("uploadId")
	chunkIndex := c.GetString("chunkIndex")
	//filename := c.GetString("filename")

	defer file.Close()

	// 创建临时目录
	tmpDir := filepath.Join("uploads", "tmp", uploadId)
	if err := os.MkdirAll(tmpDir, 0755); err != nil {
		c.Data["json"] = map[string]interface{}{"error": "目录创建失败"}
		c.ServeJSON()
		return
	}

	// 保存分片文件
	dstPath := filepath.Join(tmpDir, chunkIndex)
	dstFile, err := os.Create(dstPath)
	if err != nil {
		c.Data["json"] = map[string]interface{}{"error": "文件创建失败"}
		c.ServeJSON()
		return
	}
	defer dstFile.Close()

	if _, err := io.Copy(dstFile, file); err != nil {
		c.Data["json"] = map[string]interface{}{"error": "文件保存失败"}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{"status": "success"}
	c.ServeJSON()
}

// 合并文件接口
func (c *UploadController) PostMerge() {
	type MergeRequest struct {
		UploadId    string `json:"uploadId"`
		Filename    string `json:"filename"`
		FilePath    string `json:"filePath"`
		CurrentPath string `json:"currentPath"`
		Version     string `json:"version"`
		Machine     int    `json:"machine"`
		ParentID    string `json:"parent_id"`
	}
	var req MergeRequest
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]any{"error": "json format error", "code": "200"}
		c.ServeJSON()
		return
	}

	if req.FilePath == "" {
		req.FilePath = filepath.Join(req.CurrentPath, req.Filename)
	}

	var finalPath string
	if !models.PathContainsDir(req.FilePath, "FileList") {
		finalPath = filepath.Join("FileList", req.FilePath)
	} else {
		finalPath = req.FilePath
	}

	if finalPath == "FileList" {
		finalPath = filepath.Join("FileList", req.Filename)
	}

	finalPath = strings.Replace(finalPath, "\\", "/", -1)
	targetDir := filepath.Dir(finalPath)

	// 创建目标目录（关键修复点）
	if err := os.MkdirAll(targetDir, 0755); err != nil { // 自动递归创建目录
		c.Data["json"] = map[string]any{"message": "目录创建失败: " + err.Error(), "code": "200"}
		c.ServeJSON()
		return
	}

	machineInfo, err := dbmgr.GlobalBaseRepo.GetMachineById(req.Machine)
	if err != nil {
		logs.Error(err.Error())
		c.Data["json"] = map[string]any{"message": "获取机台信息失败: " + err.Error(), "code": "200"}
		c.ServeJSON()
		return
	}

	arrayPath := models.HandleFileUpload(machineInfo.Code, req.Version, finalPath)

	parentid := "process"
	if req.ParentID == "conf" {
		parentid = "conf"
	}

	for _, pathItem := range arrayPath {
		parentid, err = dbmgr.GlobalBaseRepo.CheckAndAddFileFolder(req.Machine, req.Version, pathItem["parentPath"], pathItem["folderName"], parentid)
		if err != nil {
			logs.Error("add folder to db failed, file: %s,err : %s", pathItem["parentPath"]+pathItem["folderName"], err.Error())
			c.Data["json"] = map[string]any{"message": "add folder info to db failed", "code": "200"}
			c.ServeJSON()
			return
		}
	}

	// 创建临时文件（添加.tmp后缀）
	tmpPath := finalPath + ".tmp"
	logs.Info("create tmp file: %s", tmpPath)
	tmpFile, err := os.Create(tmpPath)
	if err != nil {
		logs.Error("临时文件创建失败, path: %s, err: %s", tmpPath, err.Error())
		c.Data["json"] = map[string]any{"message": "临时文件创建失败: " + err.Error(), "code": "200"}
		c.ServeJSON()
		return
	}
	defer func() {
		tmpFile.Close() // 确保文件句柄关闭
		// 如果临时文件仍存在则清理
		if _, err := os.Stat(tmpPath); err == nil {
			os.Remove(tmpPath)
		}
	}()

	// 合并分片到临时文件
	tmpDir := filepath.Join("uploads", "tmp", req.UploadId)
	for i := 0; ; i++ {
		chunkPath := filepath.Join(tmpDir, strconv.Itoa(i))
		chunkFile, err := os.Open(chunkPath)
		if err != nil {
			if os.IsNotExist(err) {
				break // 正常结束
			}
			logs.Error("分片文件打开失败: %s", err.Error())
			c.Data["json"] = map[string]any{"message": "分片文件异常: " + err.Error(), "code": "200"}
			c.ServeJSON()
			return
		}

		logs.Info("copy chunkfile: %s to path: %s", chunkPath, tmpPath)
		if _, err := io.Copy(tmpFile, chunkFile); err != nil {
			chunkFile.Close()
			logs.Error("文件合并失败: %s", err.Error())
			c.Data["json"] = map[string]any{"message": "文件合并失败: " + err.Error(), "code": "200"}
			c.ServeJSON()
			return
		}
		chunkFile.Close()
		os.Remove(chunkPath) // 及时清理已合并分片
	}

	os.Remove(tmpDir)

	// 确保所有数据落盘
	if err := tmpFile.Sync(); err != nil {
		logs.Error("文件同步失败: %s", err.Error())
		c.Data["json"] = map[string]any{"message": "文件同步失败: " + err.Error(), "code": "200"}
		c.ServeJSON()
		return
	}

	tmpFile.Close() // 显式关闭以便后续操作

	//md5Cache
	md5Str, err := models.CalculateFileMD5(tmpPath)
	if err != nil {
		logs.Error("文件合并失败,获取文件md5值失败: %s", err.Error())
		c.Data["json"] = map[string]any{"message": "文件合并失败,获取文件md5值失败: " + err.Error(), "code": "200"}
		c.ServeJSON()
		return
	}

	versionInfo := dbmgr.Version{
		Id: req.Version,
	}

	fileInfoTemp, err := os.Stat(tmpPath)
	if err != nil {
		logs.Error(err.Error())
		c.Data["json"] = map[string]any{"message": "文件合并失败,获取文件大小失败: " + err.Error(), "code": "200"}
		c.ServeJSON()
		return
	}

	// 原子替换最终文件（跨平台兼容方案）
	if err := models.AtomicReplace(tmpPath, finalPath); err != nil {
		logs.Error("文件替换失败: %s", err.Error())
		c.Data["json"] = map[string]any{"message": "文件替换失败: " + err.Error(), "code": "200"}
		c.ServeJSON()
		return
	}

	pathIndex, _ := filepath.Split(finalPath)

	fileInfo := dbmgr.File{
		FileName: req.Filename,
		Path:     pathIndex,
		MD5:      md5Str,
		FileSize: fileInfoTemp.Size(),
		Version:  &versionInfo,
		Machine:  machineInfo,
		ParentId: parentid,
	}

	fileID, _, err := dbmgr.GlobalBaseRepo.CheckUniqueAndGetID(fileInfo.FileName, versionInfo.Id, fileInfo.Path)
	if err != nil {
		strErrMsg := "数据库错误，获取唯一约束数据失败 err:" + err.Error()
		logs.Error(strErrMsg)
		c.Data["json"] = map[string]any{"path": finalPath, "message": strErrMsg, "code": "200"}
		c.ServeJSON()
		return
	}

	if fileID != "" {
		mapFileInfo := map[string]interface{}{
			"MD5": fileInfo.MD5,
		}
		dbmgr.GlobalBaseRepo.UpdateFileByID(fileID, mapFileInfo)
	} else {
		_, err = dbmgr.GlobalBaseRepo.AddFile(&fileInfo)
		if err != nil {
			strErrMsg := "添加文件信息到数据库失败,err:" + err.Error()
			logs.Error(strErrMsg)
			c.Data["json"] = map[string]any{"path": finalPath, "message": strErrMsg, "code": "200"}
			c.ServeJSON()
			return
		}

		err = dbmgr.GlobalBaseRepo.UpdateVersionFilesMD5(fileInfo.Version.Id)
		if err != nil {
			logs.Error(err.Error())
			c.Data["json"] = map[string]any{"path": finalPath, "message": err.Error(), "code": "200"}
			c.ServeJSON()
			return
		}
	}

	c.Data["json"] = map[string]any{"path": finalPath, "message": "success", "code": "0"}
	c.ServeJSON()
}

type AuthController struct {
	web.Controller
}

// 请求参数结构体
type LoginRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

// 响应结构体
type LoginResponse struct {
	Code string      `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

// @Title UserLogin
// @Description 用户登录接口
// @Param   body    body    controllers.LoginRequest  true    "登录凭证"
// @Success 200 {object} controllers.LoginResponse
// @router /login [post]
func (c *AuthController) Login() {
	// 解析请求参数
	var req LoginRequest
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
		c.Data["json"] = LoginResponse{
			Code: "1",
			Msg:  "参数解析失败",
		}
		c.ServeJSON()
		return
	}
	//c.Ctx.Request.RemoteAddr

	// 参数验证
	if req.Username == "" || req.Password == "" {
		c.Data["json"] = LoginResponse{
			Code: "2",
			Msg:  "用户名和密码不能为空",
		}
		c.ServeJSON()
		return
	}

	// 调用服务层验证（这里模拟数据库验证）
	employee, err := dbmgr.GlobalBaseRepo.Login(req.Username, req.Password)
	if err != nil {
		c.Data["json"] = LoginResponse{
			Code: "3",
			Msg:  "用户名或密码错误",
		}
	} else {

		// 生成Token
		token := dbmgr.AuthToken{
			User:       employee,
			Token:      models.GenerateSecureToken(),     // 见下方生成方法
			ExpiredAt:  time.Now().Add(30 * time.Minute), // 有效期24小时
			ClientInfo: models.GetClientInfo(c.Ctx),      // 获取客户端信息
		}

		strToken, err := dbmgr.GlobalBaseRepo.AddAuthToken(&token)
		if err != nil {
			logs.Error("插入token失败: %s", err.Error())
			c.Data["json"] = LoginResponse{
				Code: "3",
				Msg:  "插入token失败",
			}
			c.ServeJSON()
			return
		}

		c.Data["json"] = LoginResponse{
			Code: "0",
			Msg:  "登录成功",
			Data: struct {
				Token string `json:"token"`
			}{Token: strToken},
		}

	}

	c.ServeJSON()
}

type UserController struct {
	beego.Controller
}

// 请求结构体
type RegisterRequest struct {
	Username   string `json:"username"`
	Password   string `json:"password"`
	Name       string `json:"name"`
	Company    string `json:"company"`
	Department string `json:"department"`
}

// 响应结构体
type ApiResponse struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

// @Title Register
// @Description 用户注册接口
// @Param   body    body    controllers.RegisterRequest  true    "用户注册信息"
// @Success 200 {object} controllers.ApiResponse
// @Failure 400 {object} controllers.ApiResponse
// @router /register [post]
func (c *UserController) Register() {
	var req RegisterRequest
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = ApiResponse{
			Code:    "400",
			Message: "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	if req.Username == "" || req.Password == "" {
		c.Data["json"] = ApiResponse{
			Code:    "401",
			Message: "用户名和密码不能为空",
		}
		c.ServeJSON()
		return
	}

	// 检查用户名是否已存在
	if exist := dbmgr.GlobalBaseRepo.CheckAccountExist(req.Username); exist {
		c.Data["json"] = ApiResponse{
			Code:    "402",
			Message: "用户名已存在",
		}
		c.ServeJSON()
		return
	}

	nCount, err := dbmgr.GlobalBaseRepo.GetEmployeeCount()
	if err != nil {
		logs.Error(err.Error())
		c.Data["json"] = map[string]interface{}{
			"code":    "200",
			"message": err.Error(),
		}
		c.ServeJSON()
		return
	}

	var employeeInfo dbmgr.Employee
	employeeInfo.Account = req.Username
	employeeInfo.Company = req.Company
	employeeInfo.Department = req.Department
	employeeInfo.Name = req.Name
	employeeInfo.Password = req.Password
	employeeInfo.Phone = req.Username
	if nCount == 0 {
		employeeInfo.IsAdmin = 1
	} else {
		employeeInfo.IsAdmin = 0
	}

	mapPermision := make(map[string]string)
	mapPermision["machineRead"] = "1"
	jsPermision, err := json.Marshal(mapPermision)
	if err != nil {
		logs.Error(err.Error())
		c.Data["json"] = ApiResponse{
			Code:    "500",
			Message: "权限信息转json字符失败",
		}

		c.ServeJSON()
		return
	}
	employeeInfo.Permission = string(jsPermision)

	_, err = dbmgr.GlobalBaseRepo.Add_Employ(&employeeInfo)
	if err != nil {
		logs.Error("注册失败:", err)
		c.Data["json"] = ApiResponse{
			Code:    "500",
			Message: "系统错误，注册失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = ApiResponse{
		Code:    "0",
		Message: "注册成功",
	}
	c.ServeJSON()
}

func (c *UserController) GetEmployeeInfo() {
	tokenStr := c.Ctx.Input.Header("Authorization")
	if tokenStr == "" {
		logs.Error("token 为空")
		c.Data["json"] = map[string]string{
			"code":    "200",
			"message": "token为空",
		}

		c.ServeJSON()
		return
	}

	tokenInfo, err := dbmgr.GlobalBaseRepo.GetByToken(tokenStr)
	if err != nil {
		logs.Error(err.Error())
		c.Data["json"] = map[string]string{
			"code":    "200",
			"message": "获取token信息失败,err:" + err.Error(),
		}
		c.ServeJSON()
		return
	}

	employeeInfo, err := dbmgr.GlobalBaseRepo.Get_employeeByID(tokenInfo.User.ID)
	if err != nil {
		logs.Error(err.Error())
		c.Data["json"] = map[string]string{
			"code":    "200",
			"message": "通过token获取用户信息失败, err:" + err.Error(),
		}

		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": "0",
		"data": employeeInfo,
	}

	c.ServeJSON()
}

func (c *UserController) GetEmployeeList() {
	lsEmployee, err := dbmgr.GlobalBaseRepo.GetAllEmployees()
	if err != nil {
		logs.Error(err.Error())

		c.Data["json"] = map[string]string{
			"code":    "200",
			"message": "获取用户列表失败, err:" + err.Error(),
		}

		c.ServeJSON()

		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": "200",
		"data": lsEmployee,
	}

	c.ServeJSON()
}

type EmployeeUpdateReq struct {
	ID         int    `json:"ID"`
	Account    string `json:"Account"`
	Password   string `json:"Password"`
	EmployeeId string `json:"EmployeeId"`
	Phone      string `json:"Phone"`
	Name       string `json:"Name"`
	Department string `json:"Department"`
	Company    string `json:"Company"`
	IsAdmin    int8   `json:"IsAdmin"`
	Permission string `json:"Permission"`
}

func (c *UserController) PostEmployeeUpdate() {
	var req EmployeeUpdateReq
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		logs.Error(err.Error())
		c.Data["json"] = ApiResponse{
			Code:    "400",
			Message: "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	mapUpdateInfo := make(map[string]interface{})
	mapUpdateInfo["Permission"] = req.Permission
	mapUpdateInfo["IsAdmin"] = req.IsAdmin
	err = dbmgr.GlobalBaseRepo.Update_Employ(req.EmployeeId, mapUpdateInfo)
	if err != nil {
		logs.Error(err.Error())

		c.Data["json"] = ApiResponse{
			Code:    "400",
			Message: "更新用户数据失败,err:" + err.Error(),
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = ApiResponse{
		Code:    "0",
		Message: "成功",
	}
	c.ServeJSON()
}

type MashineListController struct {
	beego.Controller
}

func (c *MashineListController) GetMachineList() {
	// 参数解析
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("pageSize", 10)
	//search := c.GetString("search")

	// 参数校验
	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 100 {
		pageSize = 10
	}

	// 查询数据
	var queryInfo dbmgr.Machine
	machineList, err := dbmgr.GlobalBaseRepo.GetMachines(&queryInfo)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": err.Error(),
		}
		c.ServeJSON()
		return
	}

	var listMashine []interface{}
	for _, dataItem := range machineList {
		employeeInfo, err := dbmgr.GlobalBaseRepo.Get_employeeByID(dataItem.CreatorId)
		if err != nil {
			logs.Error(err)
			c.Data["json"] = map[string]interface{}{
				"code":    500,
				"message": err.Error(),
			}
			c.ServeJSON()
			return
		}

		strTimeFormat, err := models.Convert2BeijingTimeFormat(dataItem.CreatedAt)
		if err != nil {
			logs.Error(err)
			c.Data["json"] = map[string]interface{}{
				"code":    500,
				"message": err.Error(),
			}
			c.ServeJSON()
			return
		}

		dataIndex := make(map[string]interface{})
		dataIndex["name"] = dataItem.Name
		dataIndex["code"] = dataItem.Code
		dataIndex["createdAt"] = strTimeFormat
		dataIndex["creator"] = employeeInfo.Account
		dataIndex["description"] = dataItem.Description
		dataIndex["id"] = dataItem.Id

		listMashine = append(listMashine, dataIndex)
	}

	// 格式化响应
	response := map[string]interface{}{
		"code":     200,
		"data":     listMashine,
		"total":    len(listMashine),
		"page":     page,
		"pageSize": pageSize,
	}
	c.Data["json"] = response
	c.ServeJSON()
}

func (c *MashineListController) PostCreateMachine() {
	// 解析 JSON 请求体
	var requestData struct {
		Name        string `json:"name"`
		Description string `json:"description"`
	}

	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
		c.Data["json"] = map[string]interface{}{"error": "无效的JSON格式"}
		c.Data["code"] = "400"
		logs.Error("无效的JSON格式, msg:%s", c.Ctx.Input.RequestBody)
		c.Ctx.ResponseWriter.WriteHeader(400)
		c.ServeJSON()
		return
	}

	var err error

	createTime := time.Now()

	tokenStr := c.Ctx.Input.Header("Authorization")
	logs.Debug("get submitter token: %s", tokenStr)
	tokenInfo, err := dbmgr.GlobalBaseRepo.GetByToken(tokenStr)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    "400",
			"message": "根据token获取用户信息失败 err:" + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 写入数据库
	machineInfo := dbmgr.Machine{
		Name:        requestData.Name,
		CreatedAt:   createTime,
		CreatorId:   tokenInfo.User.ID,
		Description: requestData.Description,
	}

	_, err = dbmgr.GlobalBaseRepo.CreateMachine(&machineInfo)
	if err != nil {
		c.Data["json"] = map[string]interface{}{"code": "400", "error": "数据库写入失败"}
		logs.Error("数据库写入失败, err:%s", err.Error())
		c.ServeJSON()
		return
	}

	// 返回成功响应
	c.Data["json"] = map[string]interface{}{
		"code":    "0",
		"message": "版本创建成功",
	}
	c.ServeJSON()
}
